package io.renren.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.wechat.pay.java.core.exception.HttpException;
import com.wechat.pay.java.core.exception.MalformedMessageException;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.service.partnerpayments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.*;
import io.renren.common.utils.Result;
import io.renren.config.WxPayAutoCertificateConfig;
import io.renren.config.WxPayConfig;
import io.renren.service.WxJsapiPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName WxPayServiceImpl
 * @Description TODO
 * @Author Jll
 * @Date 2024/6/18 16:33
 * @Version 1.0
 */
@Service
@Slf4j
public class WxJsapiPayServiceImpl implements WxJsapiPayService {

    @Resource
    private WxPayAutoCertificateConfig wxPayAutoCertificateConfig;

    @Resource
    private WxPayConfig wxPayConfig;

    private final ReentrantLock lock = new ReentrantLock();



    @Override
    public Result<Map<String, Object>> partnerPaymentsJsapiPay() {
        JsapiServiceExtension service =
                new JsapiServiceExtension.Builder()
                        .config(wxPayAutoCertificateConfig.rsaAutoCertificateConfig()).build();
        PrepayWithRequestPaymentResponse response;
        try {
            BigDecimal totalFee = new BigDecimal("0.01");
            String orderNo = IdUtil.simpleUUID();
            PrepayRequest request = new PrepayRequest();
            //服务商公众号id
            request.setSpAppid(wxPayConfig.getGzhAppId());
            //服务商商户号id
            request.setSpMchid(wxPayConfig.getMerchantId());
            //二级商户id
            request.setSubMchid("1673936453");
            //二级商户应用的appid
            request.setSubAppid("wx2c92afba3cab38b6");
            request.setDescription("支付手续费");
            request.setOutTradeNo(orderNo);
            request.setNotifyUrl(wxPayConfig.getPayNotifyUrl());
            Amount amount = new Amount();
            amount.setTotal(totalFee.multiply(new BigDecimal("100")).intValue());
            request.setAmount(amount);
            Payer payer = new Payer();
            //payer.setSpOpenid("");
            //服务商小程序应用下的openId
            payer.setSubOpenid("oCdAW7ZGR-x_WmrdwWs_-aSp5qFo");
            request.setPayer(payer);
            log.info("请求预支付下单，请求参数：{}", JSONObject.toJSONString(request));
            // 调用预下单接口
            //服务商下的小程序应用appId
            response = service.prepayWithRequestPayment(request, request.getSpAppid());
            log.info("订单【{}】发起预支付成功，返回信息：{}", orderNo, response);
        } catch (HttpException e) { // 发送HTTP请求失败
            log.error("微信下单发送HTTP请求失败，错误信息：{}", e.getHttpRequest());
            return new Result<Map<String, Object>>().error("下单失败");
        } catch (ServiceException e) { // 服务返回状态小于200或大于等于300，例如500
            log.error("微信下单服务状态错误，错误信息：{}", e.getErrorMessage());
            return new Result<Map<String, Object>>().error("下单失败");
        } catch (MalformedMessageException e) { // 服务返回成功，返回体类型不合法，或者解析返回体失败
            log.error("服务返回成功，返回体类型不合法，或者解析返回体失败，错误信息：{}", e.getMessage());
            return new Result<Map<String, Object>>().error("下单失败");
        }
        Map<String, Object> map = new HashMap<>(1);
        map.put("data", response);
        return new Result<Map<String, Object>>().ok(map);
    }

    @Override
    public Map<String, Object> queryOrderByOutTradeNo(String outTradeNo) {
        JsapiServiceExtension service =
                new JsapiServiceExtension.Builder()
                        .config(wxPayAutoCertificateConfig.rsaAutoCertificateConfig()).build();
        QueryOrderByOutTradeNoRequest queryOrderByOutTradeNoRequest = new QueryOrderByOutTradeNoRequest();
        queryOrderByOutTradeNoRequest.setOutTradeNo(outTradeNo);
        queryOrderByOutTradeNoRequest.setSpMchid(wxPayConfig.getMerchantId());
        //子商户mechId
        queryOrderByOutTradeNoRequest.setSubMchid("1673936453");
        Transaction transaction = service.queryOrderByOutTradeNo(queryOrderByOutTradeNoRequest);
        Map<String, Object> map = new HashMap<>(1);
        map.put("tradeState", transaction.getTradeState());
        return map;
    }

}
